<template>
  <el-dialog
    :visible.sync="authorizeVisible"
    :close-on-click-modal="false"
    title="授权"
    width="600px"
    @close="close"
  >
    <div
      v-loading="loading"
      class="flex-y-center dialog"
      element-loading-text="正在加载授权..."
    >
      <!--      <div class="big-tips">请输入授权密码或者让管理员扫码授权后继续</div>-->
      <div class="big-tips">请让管理员扫码授权后继续</div>
      <div v-loading="wxLoading" class="qrcode">
        <el-image v-if="qrcodeUrl" :src="qrcodeUrl" alt />
        <div v-else style="background-color:#000;" class="refresh" />
        <div v-if="isQrcodeExpire" class="refresh flex-x-center-center" style="cursor: pointer" @click="getQrCode">
          <p>
            二维码已失效
            <br>点击刷新
          </p>
        </div>
        <div v-if="isScan" class="refresh flex-x-center-center">
          <p>
            正在授权...
          </p>
        </div>
      </div>
      <div class="small-tips">二维码5分钟内有效，请不要关闭页面</div>
      <!--      <div class="small-tips">或者在此处输入授权密码</div>-->
      <!--      <div class="refund-psw">-->
      <!--        <PassWordBox ref="passWordBox" @sendPsw="sendPsw" />-->
      <!--      </div>-->
      <!--      <el-button plain>没有授权密码？点击获取</el-button>-->
    </div>
  </el-dialog>
</template>

<script>
import { getAuthQrcode, queryAuthState, verifyAuthor } from '@/api/authentication'
import { getCookies, setCookies } from '@/utils/auth'

export default {
  data() {
    return {
      loading: false,
      authorizeVisible: false,
      qrcodeUrl: '', // 二维码地址
      qrcodeNo: '',
      qrcodeContent: '',
      wxLoading: false,
      isQrcodeExpire: true, // 刷新提示
      isScan: false, // 已扫描
      isStopCheckQrcodeState: false, // 停止轮询
      sceneStr: '' // 场景值
    }
  },
  methods: {
    // 弹框相关
    open(sceneStr) {
      console.log(sceneStr)
      this.sceneStr = sceneStr
      this.checkAuthToken()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.authorizeVisible = true
    },

    close() {
      this.reject()
      this.reject = null
      this.loading = false
      this.isScan = false
      this.isQrcodeExpire = true
      this.isStopCheckQrcodeState = true
    },

    checkAuthToken() {
      const data = {}
      if (getCookies(this.sceneStr)) {
        data.authToken = getCookies(this.sceneStr)
      }
      data.sceneStr = this.sceneStr
      verifyAuthor(data).then((res) => {
        if (res.data) {
          this.resolve()
          this.resolve = null
        } else {
          this.getQrCode()
          this.show()
        }
      }).catch(() => {})
    },

    // 获取二维码
    getQrCode() {
      this.isStopCheckQrcodeState = false
      this.wxLoading = true
      const data = {
        qrcodeType: 0, // 二维码登录类型, 0:微信
        sceneStr: this.sceneStr,
        scope: 2 // 指定登录, 0:付惠吧后台, 1:服务商后台, 2:商家后台
      }
      getAuthQrcode({ data }).then(res => {
        this.qrcodeUrl = res.data.qrcodeUrl
        this.qrcodeNo = res.data.qrcodeNo
        this.qrcodeContent = res.data.qrcodeContent
        // 关闭刷新提示
        this.isQrcodeExpire = false
        // 检查状态
        this.checkMchQrcodeState()
      }).finally(() => {
        this.wxLoading = false
      })
    },

    // 轮询获取当前二维码状态
    checkMchQrcodeState() {
      const params = {
        qrcodeNo: this.qrcodeNo
      }
      queryAuthState(params)
        .then(res => {
          console.log(res)
          this.isScan = res.data.state === 1
          switch (res.data.state) {
            case 0: // 0.未扫码,轮询状态 2000ms
            case 1: { // 1.授权中,轮询状态 2000ms
              const timerId = setTimeout(() => {
                if (this.isStopCheckQrcodeState) return clearTimeout(timerId)
                this.checkMchQrcodeState()
              }, 2000)
              break
            }
            case 3: // 3.授权结束，停止轮询
              if (res.data.result) {
                if (res.data.authToken && res.data.time) {
                  const expires = this.$momentMini().add(Number(res.data.time), 'minute').toDate()
                  setCookies(this.sceneStr, res.data.authToken, new Date(expires).toUTCString())
                }
                this.resolve()
                this.resolve = null
                this.authorizeVisible = false
              } else {
                this.$message({
                  type: 'error',
                  message: '管理员拒绝授权!'
                })
                this.reject()
                this.reject = null
                this.authorizeVisible = false
              }
              this.isStopCheckQrcodeState = true
              break
            default: // 2.码过期,显示刷新提示
              this.isScan = false
              this.isQrcodeExpire = true
              this.isStopCheckQrcodeState = true
              break
          }
        })
        .catch(() => {
          this.isQrcodeExpire = true
          this.isStopCheckQrcodeState = true
        })
        .finally(() => {
        })
    }

    // 发送授权吗
    // sendPsw(val) {
    //   console.log(val)
    //   if (val.length === 6) {
    //     this.loading = true
    //     setTimeout(() => {
    //       if (val === '123456') {
    //         setCookies(this.tokenName, val, this.$dayjs().add(10, 'minute'))
    //         this.$message({
    //           type: 'success',
    //           message: '验证成功!'
    //         })
    //         this.resolve()
    //         this.resolve = null
    //         this.authorizeVisible = false
    //       } else {
    //         this.$message({
    //           type: 'error',
    //           message: '验证失败!'
    //         })
    //         this.$refs.passWordBox.defaultPsw()
    //       }
    //       this.$refs.passWordBox.defaultPsw()
    //       this.loading = false
    //     }, 3000)
    //   }
    // }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dialog {
  padding-bottom: 20px;
  .qrcode {
    position: relative;
    width: 205px;
    height: 205px;
    margin: 40px auto;

    .el-image {
      height: 100%;
      border: 1px solid #eee;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
  }

  .refresh {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    line-height: 30px;
    background: #333;
    font-size: 18px;
    opacity: 0.8;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }

  .refund-psw {
    margin: 30px 0;
  }

  .big-tips {
    margin-top: 25px;
    font-size: 18px;
    text-align: center;
    color: #333;
  }

  .small-tips {
    font-size: 14px;
    text-align: center;
    color: #909399;
  }

  .el-button {
    border: none;
    color: #2A70F2;
    font-weight: bold;
    border-radius: 20px;
    &:hover {
      background-color: #dde9fc;
    }
    &:active {
      background-color: #edf2ff;
    }
  }
}
</style>
